package com.habdqn.easybuy.dao.impl;

import com.habdqn.easybuy.dao.BaseDao;
import com.habdqn.easybuy.dao.NewsDao;
import com.habdqn.easybuy.entity.News;
import com.habdqn.easybuy.util.Page;
import com.habdqn.easybuy.util.StringUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Xing.Jiejian
 * @date 2020/11/28
 */
public class NewsDaoImpl extends BaseDao implements NewsDao {
    private final String baseSelect = "SELECT id, title, content, create_time, user_id FROM news";

    @Override
    public News queryById(Integer id) {
        String sql = baseSelect + " WHERE id=?";
        List<News> newsList = getListByRS(executeQuery(sql, id));
        if (newsList != null && newsList.size() > 0) {
            return newsList.get(0);
        }
        return null;
    }

    @Override
    public List<News> queryAllByLimit(int offset, int limit) {
        String sql = baseSelect + " LIMIT ?,?";
        return getListByRS(executeQuery(sql, offset, limit));
    }

    @Override
    public List<News> queryAll(News news, Page<News> page) {
        StringBuilder sql = new StringBuilder(baseSelect);
        List<Object> paramList = buildQueryConditions(news, sql);
        buildPageQuery(sql,paramList,page);
        return getListByRS(executeQuery(sql.toString(), paramList.toArray()));
    }



    @Override
    public int insert(News news) {
        String sql = "INSERT INTO news(title, content, create_time, user_id) VALUES(?, ?, ?, ?)";
        Object[] params = {news.getTitle(), news.getContent(), news.getCreateTime(), news.getUserId()};
        return executeInsert(sql, params);
    }

    @Override
    public int update(News news) {
        String sql = "UPDATE news SET title=?, content=?, create_time=?, user_id=? WHERE id=?";
        Object[] params = {news.getTitle(), news.getContent(), news.getCreateTime(), news.getUserId(), news.getId()};
        return executeUpdate(sql, params);
    }

    @Override
    public int deleteById(Integer id) {
        String sql = "DELETE FROM news WHERE id=?";
        return executeUpdate(sql, id);
    }

    @Override
    public int getTotal(News news) {
        StringBuilder sql = new StringBuilder("SELECT COUNT(id) FROM news");
        List<Object> paramList = buildQueryConditions(news, sql);
        return (int) (long) uniqueResult(sql.toString(), paramList.toArray());
    }

    /**
     * 从结果集中提取对象集合
     *
     * @param rs 结果集
     * @return 新闻集合
     */
    private List<News> getListByRS(ResultSet rs) {
        List<News> newsList = null;
        try {
            if (rs != null) {
                newsList = new ArrayList<>();
                while (rs.next()) {
                    News news = new News();
                    news.setId(rs.getInt("id"));
                    news.setTitle(rs.getString("title"));
                    news.setContent(rs.getString("content"));
                    news.setCreateTime(rs.getDate("create_time"));
                    news.setUserId(rs.getInt("user_id"));
                    newsList.add(news);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }
        return newsList;
    }

    /**
     * 组装新闻查询条件
     * @param news 新闻条件
     * @param sql 原始SQL
     * @return 参数集合
     */
    private List<Object> buildQueryConditions(News news, StringBuilder sql) {
        List<Object> paramList = new ArrayList<>();
        if (news != null) {
            sql.append(" WHERE 1=1 ");
            if (news.getId() != null && news.getId() > 0) {
                sql.append(" AND id=? ");
                paramList.add(news.getId());
            }
            if (StringUtils.isNotBlank(news.getTitle())) {
                sql.append(" AND title LIKE ? ");
                paramList.add("%" + news.getTitle() + "%");
            }
            // 一般不查询内容（新闻内容太多，一般需要全文索引或者搜索引擎）
            if (news.getCreateTime() != null) {
                sql.append(" AND create_time=? ");
                paramList.add(news.getCreateTime());
            }
            if (news.getUserId() != null && news.getUserId() > 0) {
                sql.append(" AND user_id=? ");
                paramList.add(news.getUserId());
            }
        }
        return paramList;
    }
}
